import cloud from './cloud';

// gather: 集合名,  query: 查询参数,  boolean: 是否显示加载框
const cloudGet = (gather, query, boolean = true, limit = 20, skip = 0) => {
  return new Promise(async (resolve, reject) => {
    const c1 = cloud();
    await c1.init();
    if (boolean) {
      wx.showLoading({
        title: 'Loading...',
      })
    }
    wx.showNavigationBarLoading();
    c1.database()
      .collection(gather)
      .where(query)
      .limit(limit)
      .skip(skip)
      .get({
        success: (res) => {
          resolve(res.data);
        },
        fail: (err) => {
          wx.showModal({
            title: '错误提示',
            content: err,
            showCancel: false,
            complete: (res) => {
              if (res.confirm) { }
            }
          })
        },
        complete: () => {
          wx.hideLoading();
          wx.stopPullDownRefresh();
          wx.hideNavigationBarLoading();
        }
      });
  })
}

const getCloudAllData = (gather, boolean = true) => {
  return new Promise(async (resolve, reject) => {
    const c1 = cloud();
    await c1.init();
    if (boolean) {
      wx.showLoading({
        title: 'Loading...',
      })
    }
    wx.showNavigationBarLoading();

    c1.callFunction({
      name: 'allData',
      data: {
        gather,
      }
    }).then((res) => {
      resolve(res.result.data);
      wx.hideLoading();
    }).catch(err => {
      reject(err);
      wx.showModal({
        title: '错误提示',
        content: err,
        showCancel: false,
        complete: (res) => {
          if (res.confirm) { }
        }
      })
    })
  })
}

module.exports = {
  cloudGet,
  getCloudAllData
}